/* eslint-disable react/no-unused-state */
import React, {Fragment, PureComponent} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import {Button, Card, Col, Divider, Dropdown, Upload, Form, Tabs, DatePicker, Icon, Input, Menu, message, Radio, Modal, Row, Select, Tree, Popconfirm} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import styles from '../search.less';
import UploadFileForm from './sub/UploadFileForm';
import {ruleP, nameMaxLength,remarkMaxLength} from '@/utils/rule'
const {TextArea} = Input;
const FormItem = Form.Item;
const {TreeNode} = Tree;
const DirectoryTree = Tree.DirectoryTree;
const TabPane = Tabs.TabPane;
const { Option } = Select;

const formLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};

const CreateForm = Form.create()(props => {
  const {
    modalVisible,
    form,
    addDataFn,
    updateFn,
    handleModalVisible,
    isDetail,
    text,
    queryRole,
    queryPassWord,
    queryLevel,
    roleByCodelist,
    } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if(text && text.orgId) {
        updateFn(fieldsValue,text);
      }else{
        addDataFn(fieldsValue);
      }
    });
  };

  if(isDetail) {
    return (
      <Modal
        destroyOnClose
        width={800}
        title="查看用户"
        visible={modalVisible}
        onCancel={() => handleModalVisible()}
        footer={[
            <Button type="primary" onClick={() => handleModalVisible()}>返回</Button>
          ]}
        className={styles.viewMore}
        >
        <Row>
          <Col md={12}>
            <FormItem {...formLayout} label="用户名">
              {text.userName}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="登录名">
              <div>{text.userCode}</div>
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="手机号">
              <div>{text.mobilePhone}</div>
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="邮箱">
              <div>{text.email}</div>
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="所属角色">
              <div style={{overflow:'hidden',whiteSpace:'nowrap',textOverflow:'ellipsis'}} title={roleByCodelist&&roleByCodelist.length?roleByCodelist.map((v) => {
                return v.roleName
              }).join(','):null}>{roleByCodelist&&roleByCodelist.length?roleByCodelist.map((v) => {
                return v.roleName
              }).join(','):null}</div>
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="所属组织">
              <div>{text.orgName}</div>
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="职级">
              <div>{text.levelName}</div>
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="出生日期">
              <div>{text.bornDate&&moment(text.bornDate).format('YYYY-MM-DD')}</div>
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="性别">
              <div>{text.sex==0?'女':text.sex==1?'男':''}</div>
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="身份证号">
              <div>{text.identityCard}</div>
            </FormItem>
          </Col>
          <Col md={24}>
            <FormItem labelCol={{span: 3}} wrapperCol={{span: 21}} label="住址">
              <div>{text.homeAddress}</div>
            </FormItem>
          </Col>

          <Col md={24}>
            <FormItem labelCol={{span: 3}} wrapperCol={{span: 21}} label="备注">
              {text.remark}
            </FormItem>
          </Col>
          </Row>
      </Modal>
    )
  }else{
    function disabledDate(current) {
      return current && current > moment().endOf('day');
    }
    const roleByCodeArr = [];
    if(roleByCodelist&&roleByCodelist.length){
      roleByCodelist.map((v) => {
        roleByCodeArr.push(v.id)
      })
    }

    return (
    <Modal
      destroyOnClose
      width={800}
      title={text?'编辑用户':'新增用户'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <Row gutter={16}>
        <Col md={12}>
          <FormItem {...formLayout} label="用户名">
          {form.getFieldDecorator('userName', {
            rules: [{ required: true, whitespace:true, message: '用户名不能为空'},
            {max:nameMaxLength()[0],message:nameMaxLength()[1]}],
              initialValue: text&&text.userName||''
          })(<Input placeholder="请输入" />)}
          </FormItem>
        </Col>

        <Col md={12}>
          <FormItem {...formLayout} label="登录名">
            {form.getFieldDecorator('userCode', {
              rules: [{ required: true, message: '登录名不能为空'},
              {max:nameMaxLength()[0],message:nameMaxLength()[1]},
              {pattern:new RegExp(ruleP(0)[0],'g'), message:ruleP(0)[1]}],
              initialValue: text&&text.userCode||''})
            (<Input placeholder="请输入" disabled={text&&text.id==null?true:false} />)}
          </FormItem>
        </Col>

        {!(text&&text.password)?<Col md={12}>
          <FormItem {...formLayout} label="初始密码">
          {form.getFieldDecorator('password', {
            rules: [{ required: true, message: '初始密码不能为空' }],initialValue: queryPassWord
          })(<Input disabled placeholder="请输入" />)}
          </FormItem>
        </Col>:null}

        <Col md={12}>
          <FormItem {...formLayout} label="所属角色">
            {form.getFieldDecorator('userRole', {
              rules: [{ required: true,message:'请选择所属角色' }],initialValue: text?roleByCodeArr:[4]
            })(<Select placeholder="请选择" style={{width: '100%'}} mode='multiple'>
              {
                queryRole.map((item,index) => {
                  return (<Option key={item.id} value={item.id}>{item.roleName}</Option>)
                })
              }
            </Select>)}
          </FormItem>
        </Col>
        <Col md={12}>
          <FormItem {...formLayout} label="手机号">
          {form.getFieldDecorator('mobilePhone', {
            rules: [{pattern:new RegExp('[1][3-8][0-9]{9}$','g'), message:'请输入11位正确格式的手机号'}],
          initialValue: text&&text.mobilePhone||''
        })(<Input placeholder="请输入" />)}
          </FormItem>
        </Col>
        <Col md={12}>
          <FormItem {...formLayout} label="邮箱">
          {form.getFieldDecorator('email', {
            rules: [{pattern:new RegExp('^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$','g'),
            message:'请输入正确格式的邮箱'}],
            initialValue: text&&text.email||''
          })(<Input placeholder="请输入" />)}
          </FormItem>
        </Col>
        <Col md={12}>
          <FormItem {...formLayout} label="职级">
            {form.getFieldDecorator('userLevel', {initialValue: text&&text.userLevel||''
            })(<Select placeholder="请选择" style={{width: '100%'}}>
              {
                queryLevel.map((item,index) => {
                  return (<Option key={item.id} value={item.levelScore}>{item.levelName}</Option>)
                })
              }
            </Select>)}
          </FormItem>
        </Col>
        {

        }


        <Col md={12}>
          <FormItem {...formLayout} label="出生日期">
          {form.getFieldDecorator('bornDate',{
            initialValue: text&&text.bornDate&&moment(text.bornDate)||null
          })(<DatePicker disabledDate={disabledDate} style={{width:'100%'}} format='YYYY-MM-DD' />)}
          </FormItem>
        </Col>
        <Col md={12}>
          <FormItem {...formLayout} label="性别">
          {form.getFieldDecorator('sex', {
            initialValue: text&&text.sex||(text&&text.sex==0?text.sex:'')
          })(
            <Radio.Group>
            <Radio value={0}>
              女
            </Radio>
            <Radio value={1}>
              男
            </Radio>
          </Radio.Group>
          )}
          </FormItem>
        </Col>
        <Col md={12}>
          <FormItem {...formLayout} label="身份证号">
          {form.getFieldDecorator('identityCard', {
            rules: [{pattern:new RegExp('^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$','g'), message:'请输入正确格式的身份证'}],
            initialValue: text&&text.identityCard||''
          })(<Input placeholder="请输入" />)}
          </FormItem>
        </Col>
        <Col md={12}>
          <FormItem {...formLayout} label="住址">
          {form.getFieldDecorator('homeAddress', {rules:[{max:remarkMaxLength()[0],message:remarkMaxLength()[1]}],
            initialValue: text&&text.homeAddress||''
          })(<TextArea rows={3} placeholder="请输入" />)}
          </FormItem>
        </Col>
        <Col md={12}>
          <FormItem {...formLayout} label="备注">
          {form.getFieldDecorator('remark', {rules:[{max:remarkMaxLength()[0],message:remarkMaxLength()[1]}],
            initialValue: text&&text.remark||''
          })(<TextArea rows={3} placeholder="请输入" />)}
          </FormItem>
        </Col>

{}
      </Row>
    </Modal>
  );
  }

});

@connect(({usermanager, loading}) => ({
  usermanager,
  loading: loading.models.usermanager,
}))


@Form.create()
class UserList extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    isDetail: false,
    text: {},
    addParmas: {}, //新增时需要左边树的参数
    // queryTitle: [], //头衔
    queryRole: [], //用户角色
    queryPassWord: '', //初始密码
    queryLevel: [], //用户职级
    updateModalVisible: false,//组织管理弹框显示与否
    uploadVisible: false, //导入窗口
    roleByCodelist: [],
  };

  columns = [
    {
      title: '用户名',
      dataIndex: 'userName',

    },
    {
      title: '登录名',
      dataIndex: 'userCode',

    },
    {
      title: '手机号',
      dataIndex: 'mobilePhone',
    },

    {
      title: '所属组织',
      dataIndex: 'orgName',
    },
    {
      title: '状态',
      render: (text, record) => {
        const status = ['正常','冻结','离职','锁定','注销'];
        return status[text.userState]
      },
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.openDetailsPage(true,text)}>详情</a>
          <Divider type="vertical"/>
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item key="edit" onClick={() => this.handleModalVisible(true,text)}>编辑</Menu.Item>
                <Menu.Item onClick={() => this.deleteData(text.userId)}>删除</Menu.Item>
              </Menu>
            }
          >
            <a>更多 <Icon type="down"/></a>
          </Dropdown>
        </Fragment>
      ),
    },
  ];

  handleUpdateModalVisible = (flag, record) => {
    const { selectedRows } = this.state;
    if(!(selectedRows&&selectedRows.length)){
      Modal.warning({title: '操作失败',content: '请选择用户'});
      return
    }
    this.setState({
      updateModalVisible: !!flag,
    });
  };

  openDetailsPage = (flag,res) => {
    this.handleModalVisible(true,res);
    this.setState({
      isDetail: true
    });
  };

  roleByCode = (userCode) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'usermanager/roleByCode',
      payload: {userCode},
      callback: (res) => {
        if(res.result == "ok") {
          this.setState({
            roleByCodelist: res.data,
          })
          // Modal.success({title: res.msg});
        }
      },
    });
  };

  setPassCheckPhone () {
    this.setState({
      passCheckPhone: true,
    })
  }
  setPassCheckEmail () {
    this.setState({
      passCheckEmail: true,
    })
  }
  setPassCheckId () {
    this.setState({
      passCheckId: true,
    })
  }

  //批量组织迁移
  handleTransfer = (orgId) => {
    const {selectedRows} = this.state;
    const userIds = selectedRows.map((item) => {
      return item.userId;
    }).join(",");
    this.handTransferUserO(userIds,orgId);
    this.handleUpdateModalVisible()
  };

  // 组织迁移方法
  handTransferUserO(userIds,orgId) {
    const { dispatch } = this.props;
    const values = {
      userIds,
      orgId
    }
    dispatch({
      type: 'usermanager/transferUserO',
      payload: values,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
          this.treeData();// 组织树查询
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
  }

  //批量设置状态
  handleMenuClick = (e) => {
    const {selectedRows} = this.state;
    if(!(selectedRows&&selectedRows.length)){
      Modal.warning({title: '操作失败',content: '请选择用户'});
      return
    }
    const userIds = selectedRows.map((item) => {
      return item.userId;
    }).join(",");

    const state = e.key;

    this.handUpdateS(userIds,state);
  };

  // 设置状态方法
  handUpdateS(userIds,state) {
    const { dispatch } = this.props;
    const values = {
      userIds,
      state
    }
    dispatch({
      type: 'usermanager/updateS',
      payload: values,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
          this.treeData();// 组织树查询
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
  }

  //批量密码重置
  batchChangePass = (rows=[]) => {
    const { selectedRows } = this.state;
    if(!(selectedRows&&selectedRows.length)){
      Modal.warning({title: '操作失败',content: '请选择用户'});
      return
    }
    const ids = rows.map((item) => {
      return item.userId;
    }).join(",");
    Modal.confirm({
      title: '密码重置',
      content: '您确定要密码重置吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleResetPass(ids),
    });
  };

  // 密码重置方法
  handleResetPass(ids) {
    const { dispatch } = this.props;
    dispatch({
      type: 'usermanager/resetPass',
      payload: {ids},
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
          this.treeData();// 组织树查询
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
  }

  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleDeleteData(id),
    });
  };

  //批量删除
  batchDelete = (rows=[]) => {
    const { selectedRows } = this.state;
    if(!(selectedRows&&selectedRows.length)){
      Modal.warning({title: '操作失败',content: '请选择用户'});
      return
    }
    const ids = rows.map((item) => {
      return item.userId;
    }).join(",");
    this.deleteData(ids);
  };

   // 删除方法
  handleDeleteData(ids) {
    const { dispatch } = this.props;
    const {formValues} = this.state;
    dispatch({
      type: 'usermanager/remove',
      payload: {ids},
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList(formValues);
          this.treeData();// 组织树查询
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
  }

  // 分页查询列表
  pageList(res,pageSize=10,pageNum=0) {
    const { dispatch } = this.props;
    const url = 'usermanager/getList';

    const values = {
      orgId: res && res.orgId?res.orgId:(this.state.addParmas.id ? this.state.addParmas.id : ''),
      userCode: res && res.userCode1 || '',
      userName: res && res.userName1 || '',
      userState: res && res.userState || '',
      email: res && res.email1 || '',
      mobilePhone:res && res.mobilePhone1 || '',
      pageSize: pageSize,
      pageNum: pageNum,
    };
    dispatch({
      type: url,
      payload: values,
      callback: (obj) => {
        if(obj.result == "ok" && res.userName) {
          this.treeData();// 组织树查询
        }
      },
    });
  }
//y页面加载完执行
  componentDidMount() {
    this.treeData();// 组织树查询
    this.pageList();//列表查询
    // this.titleData();//头衔
    this.roleData();//用户角色
    this.passWordData();//初始密码
    this.levelData();//用户职级
  }

  // 组织树请求
  treeData() {
    const {dispatch} = this.props;
    dispatch({
      type: 'usermanager/getTree',
    });
  }

  // 头衔
  // titleData() {
  //   const {dispatch} = this.props;
  //   dispatch({
  //     type: 'usermanager/title',
  //     callback: (obj) => {
  //       if(obj.result == "ok") {
  //         this.setState({
  //           queryTitle: obj.data
  //         })
  //       }
  //     },
  //   });
  // }

  // 用户角色
  roleData() {
    const {dispatch} = this.props;
    dispatch({
      type: 'usermanager/role',
      callback: (obj) => {
        if(obj.result == "ok") {
          this.setState({
            queryRole: obj.data
          })
        }
      },
    });
  }

  // 初始密码
  passWordData() {
    const {dispatch} = this.props;
    dispatch({
      type: 'usermanager/passWord',
      callback: (obj) => {
        if(obj.result == "ok") {
          this.setState({
            queryPassWord: obj.msg
          })
        }
      },
    });
  }

  // 用户职级
  levelData() {
    const {dispatch} = this.props;
    dispatch({
      type: 'usermanager/level',
      callback: (obj) => {
        if(obj.result == "ok") {
          this.setState({
            queryLevel: obj.data
          })
        }
      },
    });
  }

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

 handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        formValues: fieldsValue,
      })
      //点击查询
      this.pageList(fieldsValue);
    });
  };

 // 新增弹框的显示和隐藏
  handleModalVisible = (flag,text) => {
    const {addParmas} = this.state;
    var parmas = JSON.stringify(addParmas);
    if(flag && parmas=="{}" && !text) {
      Modal.warning({title: "请先选择左边的组织"});
      return
    }
    if(flag && text){
      this.roleByCode(text.userCode);
    }
    if(!flag) {
      this.setState({
        roleByCodelist: [],
      })
    }
    this.setState({
      modalVisible: !!flag,
      isDetail: false,
      text: text,
    });
  };

  // 新增导入的显示和隐藏
  handleUploadVisible = (flag) => {
    const {addParmas} = this.state;
    var parmas = JSON.stringify(addParmas);
    if(flag && parmas=="{}") {
      Modal.error({title: "请先选择左边的组织"});
      return
    }
    this.setState({
      uploadVisible: !!flag,
    });
  };

   // 更新接口
  updateFn = (fields,text) => {
    const { dispatch } = this.props;
    const bornDate = fields.bornDate&&moment(fields.bornDate._d).format('YYYY-MM-DD');
    const params = {
      orgId: text.orgId,
      userId: text.userId,
      userCode: text.userCode,
      userName:fields.userName,
      password:fields.password,
      mobilePhone:fields.mobilePhone,
      email:fields.email,
      userLevel:fields.userLevel,
      // userTitle:fields.titleName,
      userRole:fields.userRole&&fields.userRole.length&&fields.userRole.join(','),
      bornDate,
      sex:fields.sex,
      identityCard:fields.identityCard,
      homeAddress:fields.homeAddress,
      remark:fields.remark,
      // userState: fields.userState,
    }
    dispatch({
      type: 'usermanager/update',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };

  // 增加接口
  addDataFn = (fields) => {
    const { dispatch } = this.props;
    const { addParmas } = this.state;
    const bornDate = fields.bornDate&&moment(fields.bornDate._d).format('YYYY-MM-DD');
    const params = {
      orgId: addParmas.id,
      userName:fields.userName,
      password:fields.password,
      mobilePhone:fields.mobilePhone,
      email:fields.email,
      userLevel:fields.userLevel,
      userCode:fields.userCode,
      // userTitle:fields.titleName,
      userRole:fields.userRole&&fields.userRole.length&&fields.userRole.join(','),
      bornDate,
      sex:fields.sex,
      identityCard:fields.identityCard,
      homeAddress:fields.homeAddress,
      remark:fields.remark,
    }
    dispatch({
      type: 'usermanager/add',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList();
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
  }; //重置

// 渲染搜索框
  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="用户名">
              {getFieldDecorator('userName1')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="登录名">
              {getFieldDecorator('userCode1')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="状态">
            {getFieldDecorator('userState')(<Select placeholder="请选择">
              <Option value=' '>全部</Option>
              <Option value='0'>正常</Option>
              <Option value='1'>冻结</Option>
              <Option value='2'>离职</Option>
              <Option value='3'>锁定</Option>
              <Option value='4'>注销</Option>
             </Select>)}
            </FormItem>
          </Col>
          </Row>
          <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="&nbsp;&nbsp;&nbsp;&nbsp;邮箱">
              {getFieldDecorator('email1')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="手机号">
              {getFieldDecorator('mobilePhone1')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  handleStandardTableChange(pagination, filters, sorter) {
    const {formValues} = this.state;
    // 分页请求
    this.pageList(formValues,pagination.pageSize,pagination.current-1);
  }

  /**
   * 选中树
   * @param id
   */
  onSelect = (e,info) => {
    const { form } = this.props;
    const props = info.node.props;
    const orgId = props.id;
    if(orgId == this.state.addParmas.id) {
      this.setState({
        addParmas: {},
      });
      return
    }
    this.pageList({orgId})
    this.setState({
      addParmas: {
        id:orgId,
      },
      formValues: {},
    });
    form.resetFields();
  };

  render() {
    const {
      usermanager: {treeList, data},
      loading,
    } = this.props;

    const {
      selectedRows,
      modalVisible,
      isDetail,
      text,
      queryRole,
      queryPassWord,
      queryLevel,
      updateModalVisible,
      uploadVisible,
      addParmas,
      roleByCodelist,
    } = this.state;

    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      isDetail: isDetail,
      addDataFn: this.addDataFn,
      updateFn: this.updateFn,
    };

    const requestData = {
      queryRole,
      queryPassWord,
      queryLevel,
    };

    const orgMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleTransfer: this.handleTransfer
    };

    const uploadMethods = {
      handleUploadVisible: this.handleUploadVisible,
      pageList: this.pageList.bind(this),
    };

    const loop = data => data.length&&data.map((item) => {
      if (item.children) {
        return (
          <TreeNode key={item.id} title={item.orgName} {...item}>
            {loop(item.children||[])}
          </TreeNode>
        );
      }
      return <TreeNode key={item.id} title={item.orgName} {...item}/>;
    });

    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="0">正常</Menu.Item>
        <Menu.Item key="1">冻结</Menu.Item>
        <Menu.Item key="2">离职</Menu.Item>
        <Menu.Item key="3">锁定</Menu.Item>
        <Menu.Item key="4">注销</Menu.Item>
      </Menu>
    );

    return (
      <PageHeaderWrapper title="用户管理">
        <GridContent className={styles.userCenter}>
          <Row gutter={24}>
            <Col lg={6} md={24}>
              <Card bordered={false} style={{marginBottom: 24}}>
                <div className={styles.treeScroll}>
                {treeList&&treeList.length?<Tree
                  showLine={true}
                  defaultExpandedKeys={['1']}
                  onSelect={this.onSelect}
                >
                  {loop(treeList||[])}

                </Tree>:null}
                </div>
              </Card>
            </Col>
            <Col lg={18} md={24}>
              <Card bordered={false}>
                <div className={styles.tableList}>
                  <div className={styles.tableListForm}>{this.renderForm()}</div>
                  <div className={styles.tableListOperator}>
                    <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                      新增
                    </Button>
                    {
                      // 暂时注释
                      // <Button icon="import" type="primary" onClick={() => this.handleUploadVisible(true)}>
                      //   导入
                      // </Button>
                    }
                    <span>
                        <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                        <Button onClick={() => this.handleUpdateModalVisible(true)} >组织迁移</Button>
                        <Button onClick={() => this.batchChangePass(selectedRows)} >密码重置</Button>
                        <Dropdown overlay={menu}>
                          <Button>
                            设置状态 <Icon type="down" />
                          </Button>
                        </Dropdown>
                      </span>
                  </div>
                  <TableList
                    className={styles.tdPadding}
                    selectedRows={selectedRows}
                    loading={loading}
                    data={data}
                    columns={this.columns}
                    onSelectRow={this.handleSelectRows}
                    onChange={this.handleStandardTableChange.bind(this)}
                    rowKey={record => record.userId}
                  />
                </div>
              </Card>
            </Col>
          </Row>
        </GridContent>

        <CreateForm
        {...parentMethods}
        modalVisible={modalVisible}
        text={text}
        {...requestData}
        roleByCodelist={roleByCodelist}
        />
        <TransferUserOrg {...orgMethods} updateModalVisible={updateModalVisible} treeList={treeList||[]}/>
        {uploadVisible?(
          <UploadFileForm {...uploadMethods} uploadVisible={uploadVisible} isUser={true} addParmas={addParmas}/>
        ):null}
      </PageHeaderWrapper>
    );
  }
}

class TransferUserOrg extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      orgId: '',
    }
  }

  onSelect = (info) => {
    this.setState({
      orgId: info[0],
    })
  };

  render() {
    const { updateModalVisible, handleUpdateModalVisible, treeList, handleTransfer } = this.props;
    const { orgId } = this.state;
    const loop = data => data.map((item) => {
      if (item.children) {
        return (
          <TreeNode key={item.id} title={item.orgName} {...item}>
            {loop(item.children||[])}
          </TreeNode>
        );
      }
      return <TreeNode key={item.id} title={item.orgName} {...item}/>;
    });
    return (
      <Modal
        width={800}
        bodyStyle={{ padding: '32px 40px 48px' }}
        destroyOnClose
        title="组织迁移"
        visible={updateModalVisible}
        onCancel={() => handleUpdateModalVisible(false)}
        onOk={() => handleTransfer(orgId)}
      >
        <Tree
          onSelect={this.onSelect}
          showLine={true}
        >
          {loop(treeList||[])}
        </Tree>

      </Modal>
    );
  }
}

export default UserList;
